var nowButton; //当前点击的按钮
var iframeObj = window.frames["iframeContent"].window
var configSpecified;
var bpmParams;
var instanceId;
var taskId;
var action;
var data;
function bpmInit(params,fn){
  var dataUrl = api + "/scabpm/bpm/task/getTaskData";// taskId=xxx
  if(!params.taskId){
    dataUrl = api + "/scabpm/bpm/instance/getInstanceData";
  }

  $.operate.post(dataUrl,
    params,
    function (res) {

      if (res.isOk){
        //iframe页面src复制
        $('#iframeContent').attr('src', res.data.form.formValue)

        //操作按钮循环显示
        buttonTemp(res.data.buttonList)
        defId = res.data.defId
        configSpecified = res.data.configSpecified
        bpmParams = Object.assign({},bpmParams,getSubmitFlowParam(res.data))
        if (res.data.task){
          instanceId = res.data.task.instId
          taskId = res.data.task.taskId
        }
        if (fn) fn()
      }else{
        $.modal.closeLoading();
      }


    }, false)

}

function getSubmitFlowParam(data){
  if(!data){
    $.modal.alertError("error");
    return;
  }

  if(data.task) {
    return {taskId:data.task.id,nodeId:data.task.nodeId,instanceId:data.task.instId};
  }

  if(data.instance){
    // started 判断是否为草稿
    return {instanceId:data.instance.id,defId:data.instance.defId,started:data.instance.actDefId};
  }

  return {
    defId: defId,
    instanceId: '',
    businessKey: ''
  }
}

function buttonClick(btn) {
	debugger
  var button = JSON.parse(decodeURI(btn))
  nowButton = JSON.parse(decodeURI(btn))
  action=nowButton.alias;
  //前置JS。此处只处理URL的，vue不经此处
  var ii = layer.load();
  var fnStr=nowButton.beforeScript;
  if(fnStr){
  var script = "var tempFunction = function(){ "+fnStr+"};"
  var result =  eval(script+"tempFunction();");
   if(result===false) {
	layer.close(ii);
	return;
     };
  }
  		
  //获取流程数据
  var busData = iframeObj.getData ? iframeObj.getData() : {};
  //表单验证不通过
  if (busData === false) {
    layer.close(ii);
    return;
  }
  data=busData;
  var validateForm = "start,agree,oppose".indexOf(nowButton.alias) != -1;

 

  if (!busData.waitIframeNotify) {
    this.postFn(nowButton);
  }
}

function postFn(button,getParamsFlag) {
  var ii = layer.load();
  var busData = iframeObj.getData ? iframeObj.getData() : {};
  var flowData = bpmParams
  flowData.data = busData;
  flowData.action = button.alias;
  if (!flowData.extendConf) {
    flowData.extendConf = {};
  }
  flowData.extendConf["nodeId"] = getQueryString("nodeId");

  //获取更多完成动作配置
  var buttonStyle = getButtonStyle(button.alias);

  // 同意，反对的时候可以自动跳过录入意见
  var requiredOpinion = configSpecified.requiredOpinion;
  if(!requiredOpinion && "oppose,agree,start".indexOf(button.alias)==-1){
    requiredOpinion = true;
  }

  if (button.destination){
    flowData.destination = button.destination
  }

  if (button.configPage && requiredOpinion) {
    layer.close(ii);
    var url = button.configPage
    var width = buttonStyle.dialogWidth
    var height = buttonStyle.dialogHeigth
    if (button.alias === 'taskOpinion'){
      url += '?id=' + instanceId
    }
    if (button.alias === 'flowImage'){
      url += '?instanceId=' + (instanceId?instanceId:'') + '&defId=' + (defId?defId:'') + '&taskId=' + (taskId?taskId:'')
      $.modal.openview(button.name, url, width, height)
      return
    }
    $.modal.open(button.name, url, width, height)
  } else {
    /*if (!flowData.opinion) {
      flowData.opinion = button.name;
    }*/
    flowData.opinion = button.opinion || button.name;

    layer.close(ii);

    if (getParamsFlag) return flowData
    postAction(flowData);
  }
}

function postAction(flowData) {
  var ii = layer.load();
  var url = flowData.taskId ? "/scabpm/bpm/task/doAction" : "/scabpm/bpm/instance/doAction";
  $.ajax({
    url: api + url,
    data: JSON.stringify(flowData),
    type: "post",
    headers:{
      'Content-Type': 'application/json;charset=UTF-8',
    },

    beforeSend: function () {
      $.modal.loading("提交中...");
    },
    success: function (res) {
      $.modal.closeLoading();
      layer.close(ii);
      var result = JSON.parse(res)
      if (!result.isOk) {
        //如果是confrms 则不提示错误
        if (handConfirms(result, flowData)) {
          $.modal.alertError(result.msg);
          console.error(result);
          return;
        }
        $.modal.alertError(result.msg);
        return;
      }
      $.modal.alertSuccess(!result.msg ? "成功" : result.msg, function(){
        window.parent.$.table.refresh();
        $.modal.close()
      });
    },
    error: function (e) {
      layer.close(ii);
    }
  })
}

function handConfirms(data, flowData) {

  // 需要二次确认
  if (data && data.code === "50103") {
    $.modal.confirm("回收任务提示", data.msg, function () {
      flowData.extendConf.confirmRecycle = true;
      postAction(flowData);
    })
    return true;
  }
  return false;
}

function execuFn(fnStr) {
  if (!fnStr) return true;

  var script = "var tempFunction = function(scope){ " + fnStr + "};"
  var result = eval(script + "tempFunction(parent);");
  if (result === false) return false;
  return true;
}

function getCustFormComponent(pageComponent) {
  for (var i = 0, c; c = pageComponent.$children[i++];) {
    if (c.$options._componentTag === "ab-custom-form") {
      return c;
    }
    // url 表单则返回父页面
    if (c.$options._componentTag === "ab-url-form") {
      return pageComponent;
    }
  }
  // 不向下递归
  console.error("页面中找不到 cust-form 的组件！！！");
  return null;
}


function getButtonStyle(alias) {
  var buttonsStyle = {
    "start": {css: "btn btn-success", icon: "fa fa-send", dialogHeigth: '', dialogWidth: 790},
    "draft": {css: "btn btn-primary", icon: "fa fa-clipboard"},
    "save": {css: "btn btn-primary ", icon: "fa fa-clipboard"},
    "agree": {css: "btn btn-success ", icon: "fa fa-check-square-o", dialogHeigth: '', dialogWidth: 790},
    "oppose": {css: "btn btn-primary", icon: "fa fa-close", dialogHeigth: '', dialogWidth: 790},
    "reject": {css: "btn btn-danger", icon: "fa fa-lastfm", dialogHeigth: '', dialogWidth: 790},
    "reject2Start": {css: "btn btn-danger", icon: "fa fa-lastfm", dialogHeigth: '', dialogWidth: 790},
    "lock": {css: "btn btn-primary ", icon: "fa fa-lock"},
    "unlock": {css: "btn btn-primary ", icon: "fa fa-unlock"},
    "taskOpinion": {css: "btn btn-primary", icon: "fa fa-navicon", dialogHeigth: '', dialogWidth: 790},
    "flowImage": {css: "btn btn-primary", icon: "fa fa-image", dialogHeigth: '', dialogWidth: 800},
    "manualEnd": {css: "btn btn-danger", icon: "fa fa-ioxhost", dialogHeigth: 322, dialogWidth: 690},
    "print": {css: "btn btn-primary ", icon: "fa fa-print", dialogHeigth: 300, dialogWidth: 500},
    'recall': {css: "btn btn-warning", icon: "fa fa-undo", dialogHeigth: '', dialogWidth: 790},
    'recover': {css: "btn btn-danger ", icon: "fa fa-reply-all", dialogHeigth: '', dialogWidth: 790},
    'reminder': {css: "btn btn-warning", icon: "fa fa-bell-o", dialogHeigth: '', dialogWidth: 790},
    'revoke': {css: "btn btn-danger ", icon: "fa fa-undo", dialogHeigth: '', dialogWidth: 790}
  }
  if (buttonsStyle[alias]) return buttonsStyle[alias];
  return {css: "btn btn-success "};
}

function buttonTemp(list, obj) {
  var btnObj = obj ? $(obj) : $('#bpmOperateBtn')
  list.forEach(function (item) {
    var strItem = encodeURI(JSON.stringify(item))
    btnObj.append('<a class="' + getButtonStyle(item.alias).css + '" onclick="buttonClick(\'' + strItem + '\')" style="margin-right: 5px;"> ' +
      '<i class="' + getButtonStyle(item.alias).icon + '"></i>  ' + item.name +
      '</a>')
  })
}

function abPrint(scope){

  // var flowRequestParam = scope.flowRequestParam;
  var url = "/bpm/instance/printDialog.html?";
  // if(flowRequestParam.instanceId){
  //   url += "instanceId="+flowRequestParam.instanceId;
  // }else if(flowRequestParam.flowKey){
  //   url += "flowKey="+flowRequestParam.flowKey;
  // }else if(flowRequestParam.defId){
  //   url += "defId="+flowRequestParam.defId;
  // }
  // window.AB_PRINT_DATA = CloneUtil.deep(scope.data);


  // url += "defId="+defId;
  // window.open(url);

  iframeObj.print()
}